package com.hudilao.controller;

import com.hudilao.common.R;
import com.hudilao.dto.StockDTO;
import com.hudilao.dto.StockLogDTO;
import com.hudilao.entity.StockLog;
import com.hudilao.service.StockLogService;
import com.hudilao.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.List;

/**
 * StockController类，处理库存管理相关请求
 */
@RestController
@RequestMapping("/stock")
@Slf4j
public class StockController {

    @Autowired
    private StockService stockService;

    @Autowired
    private StockLogService stockLogService;

    /**
     * 管理端：分页查询库存信息，可根据菜品名称过滤
     * @param page 页码
     * @param pageSize 每页记录数
     * @param dishName 菜品名称（可选）
     * @return 包含分页库存信息的响应
     */
    @GetMapping("/page")
    public R<Page<StockDTO>> queryStock(int page, int pageSize, String dishName) {

        //调用service分页查询函数
        Page<StockDTO> stockPage = stockService.queryStock(page, pageSize, dishName);

        return R.success(stockPage);
    }


    /**
     * 管理端：增加指定菜品的库存数量
     * @param dishId 菜品id
     * @param quantity 增加的库存数量
     * @return 操作结果的响应
     */
    @PostMapping("/add")
    public R<String> addStock(@RequestParam Long dishId, @RequestParam Integer quantity) {

        stockService.addStock(dishId, quantity);

        return R.success("增加库存成功");
    }


    /**
     * 管理端：减少指定菜品的库存数量
     * @param dishId 菜品ID
     * @param quantity 减少的库存数量
     * @return 操作结果的响应
     */
    @PostMapping("/reduce")
    public R<String> reduceStock(@RequestParam Long dishId, @RequestParam Integer quantity) {
        //减少库存
        try {
            stockService.reduceStock(dishId, quantity);
            return R.success("减少库存成功");

        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }

//    //管理端：查看菜品的库存记录
//    @GetMapping("/logs/{dishId}")
//    public R<List<StockLogDTO>> getStockLogs(@PathVariable Long dishId) {
//
//        //返回库存记录
//        List<StockLogDTO> stockLogs = stockLogService.getStockLogsByDishId(dishId);
//
//        return R.success(stockLogs);
//    }

    @GetMapping("/logs")
    public R<Page<StockLogDTO>> queryStockLogs(
            @RequestParam(value = "dishId", required = false) Long dishId,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        // 返回库存记录分页查询结果
        Page<StockLogDTO> stockLogs = stockLogService.queryStockLogs(dishId, page, pageSize);

        System.out.println("Received dishId: " + dishId);
        System.out.println("Received page: " + page);
        System.out.println("Received pageSize: " + pageSize);
        return R.success(stockLogs);
    }
}

